package com.wuliming.gulimall.product.exception;

import com.wuliming.common.utils.R;
import com.wuliming.exception.ExceptionCodeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.List;


@RequiredArgsConstructor
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        List<FieldError> errors = e.getBindingResult().getFieldErrors();
        HashMap<String, String> map = new HashMap<>();
        errors.stream().forEach(item -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        log.error("参数校验异常:{},异常类型：{}", e.getMessage(),e.getClass());
        return R.error(ExceptionCodeEnum.VALID_ERROR).put("data", map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        log.error("异常信息:{},异常类型：{}", e.getMessage(),e.getClass());
        return R.error(ExceptionCodeEnum.SYSTEM_ERROR);
    }
}